#! /usr/bin/env tclsh

# ----------------------------------------------------------------------------
# 
# Tcl library.
#
# yqm_leaf@163.com
# 
# 05/06/21
#
# ----------------------------------------------------------------------------

package require Expect

#
# ssh auto login.
#
proc login {ip user pass {timeout ""}} {

    global _prompt

    spawn ssh $ip -l $user

    expect {
        -re "yes/no" {
            send "yes\r"
            exp_continue
        }
        -re ".*ssword" {
            send "$pass\r"
            exp_continue
        }
        -re "$_prompt" {}
        eof {
            puts stderr "Login ended."
        } timeout {
            puts stderr "Login timeout."
        }
    }

    return $spawn_id
}

#
#
# Check if input is a valid IPv4 address.
#
proc valid_ipv4 {ip} {
    if {[regexp {^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$} $ip -\
        b1 b2 b3 b4]} {
            foreach byte "$b1 $b2 $b3 $b4" {
                if {$byte > 255} { return false }
            }
            return true
        }
    return false
}

